<%@ page language="java" import="weaver.conn.RecordSet" pageEncoding="UTF-8" %>
<%@ page import="java.util.Map" %>
<%@ page import="weaver.general.BaseBean" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="com.alibaba.fastjson.JSONObject" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="weaver.common.DateUtil" %>
<%@ page import="java.util.UUID" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Date" %>
<%@ page import="org.apache.http.impl.client.CloseableHttpClient" %>
<%@ page import="org.apache.http.impl.client.HttpClients" %>
<%@ page import="org.apache.http.client.methods.HttpGet" %>
<%@ page import="org.apache.http.client.config.RequestConfig" %>
<%@ page import="org.apache.http.client.methods.CloseableHttpResponse" %>
<%@ page import="org.apache.http.HttpStatus" %>
<%@ page import="org.apache.http.HttpEntity" %>
<%@ page import="org.apache.http.util.EntityUtils" %>
<%@ page import="java.io.IOException" %>
<script type="text/javascript">
    /*
    * 请在下面编写JS代码
    */
    var sjtzmc_fieldid1 = ModeForm.convertFieldNameToId("sjtzmc", "detail_1");//设计图纸名称
    var cljhzl_fieldid1 = ModeForm.convertFieldNameToId("cljhzl", "detail_1");//材料计划重量
    var sjtzmc_fieldid2 = ModeForm.convertFieldNameToId("sjtzmc", "detail_2");//设计图纸名称
    var sl_fieldid2 = ModeForm.convertFieldNameToId("sl", "detail_2");//数量
    ModeForm.bindDetailFieldChangeEvent(sjtzmc_fieldid2 + "," + sl_fieldid2, function (id, rowIndex, value) {
        var sjtzmcvalue = ModeForm.getFieldValue(sjtzmc_fieldid2 + "_" + rowIndex);
        var slvalue = ModeForm.getFieldValue(sl_fieldid2 + "_" + rowIndex);
        if (sjtzmcvalue != "" && slvalue != "") {
            calDtlData();
        }
    });
    function calDtlData(){
        var dtl1 = ModeForm.getDetailAllRowIndexStr("detail_1").split(",");
        for (var i = 0; i < dtl1.length; i++) {
            var sjtzmcvalue1 = ModeForm.getFieldValue(sjtzmc_fieldid1 + "_" + dtl1[i]);
            var dtl2 = ModeForm.getDetailAllRowIndexStr("detail_2").split(",");
            var values = 0.00;
            for(var j = 0; j < dtl2.length; j++){
                var sjtzmcvalue2 = ModeForm.getFieldValue(sjtzmc_fieldid2 + "_" + dtl2[j]);
                if(sjtzmcvalue1==sjtzmcvalue2){
                    var slvalue2 = ModeForm.getFieldValue(sl_fieldid2 + "_" + dtl2[j]);
                    values += slvalue2;
                }
            }
            ModeForm.changeFieldValue(cljhzl_fieldid1 + "_" + dtl1[i], {value: values});
        }
    }
</script>

<style type="text/css">
    /*
    * 请在下方编辑CSS
    */

</style>
<%
    Map<String, Object> apidatas = new HashMap<String, Object>();
    BaseBean baseBean = new BaseBean();
    String addressIP = Util.getIpAddr( request );
    String keyword = Util.null2String( request.getParameter( "keyword" ) );
    JSONObject datas = new JSONObject();
    try {
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        rs.executeQuery( "select * from uf_tycqyxx where name=?", keyword );
        if (rs.next()) {
            out.println( "-------------------------11111<br/>" );
            String currentdate = Util.null2String( rs.getString( "currentdate" ) );//当前日期
            String mainid = Util.null2String( rs.getString( "id" ) );//mainid
            long days = getDays( currentdate.substring( 0, 10 ) );
            out.print( "days ==" + days );
            if (days < 90) {
                String historyNames = Util.null2String( rs.getString( "historyNames" ) );//曾⽤名
                String regStatus = Util.null2String( rs.getString( "regStatus" ) );//企业状态
                String cancelDate = Util.null2String( rs.getString( "cancelDate" ) );//注销⽇期
                String regCapital = Util.null2String( rs.getString( "regCapital" ) );//注册资本
                String city = Util.null2String( rs.getString( "city" ) );//市
                String staffNumRange = Util.null2String( rs.getString( "staffNumRange" ) );//⼈员规模
                String industry = Util.null2String( rs.getString( "industry" ) );//⾏业
                String historyNameList = Util.null2String( rs.getString( "historyNameList" ) );//曾⽤名列表
                String bondNum = Util.null2String( rs.getString( "bondNum" ) );//股票号
                String type = Util.null2String( rs.getString( "type1" ) );//法⼈类型，1 ⼈ 2 公司
                String bondName = Util.null2String( rs.getString( "bondName" ) );//股票名
                String updateTimes = Util.null2String( rs.getString( "updateTimes" ) );//更新时间
                String revokeDate = Util.null2String( rs.getString( "revokeDate" ) );//吊销⽇期
                String legalPersonName = Util.null2String( rs.getString( "legalPersonName" ) );//法⼈
                String revokeReason = Util.null2String( rs.getString( "revokeReason" ) );//吊销原因
                String regNumber = Util.null2String( rs.getString( "regNumber" ) );//注册号
                String property3 = Util.null2String( rs.getString( "property3" ) );//英⽂名
                String creditCode = Util.null2String( rs.getString( "creditCode" ) );//统⼀社会信⽤代码
                String usedBondName = Util.null2String( rs.getString( "usedBondName" ) );//股票曾⽤名
                String fromTime = Util.null2String( rs.getString( "fromTime" ) );//经营开始时间
                String approvedTime = Util.null2String( rs.getString( "approvedTime" ) );//核准时间
                String socialStaffNum = Util.null2String( rs.getString( "socialStaffNum" ) );//参保⼈数
                String alias = Util.null2String( rs.getString( "alias" ) );//简称
                String companyOrgType = Util.null2String( rs.getString( "companyOrgType" ) );//企业类型
                String actualCapitalCurrency = Util.null2String( rs.getString( "actualCapitalCurrency" ) );//实收注册资本币种 ⼈⺠币 美元 欧元 等
                String qyid = Util.null2String( rs.getString( "qyid" ) );//企业id
                String orgNumber = Util.null2String( rs.getString( "orgNumber" ) );//组织机构代码
                String cancelReason = Util.null2String( rs.getString( "cancelReason" ) );//注销原因
                String toTime = Util.null2String( rs.getString( "toTime" ) );//经营结束时间
                String actualCapital = Util.null2String( rs.getString( "actualCapital" ) );//实收注册资⾦
                String estiblishTime = Util.null2String( rs.getString( "estiblishTime" ) );//成⽴⽇期
                String regInstitute = Util.null2String( rs.getString( "regInstitute" ) );//登记机关
                String taxNumber = Util.null2String( rs.getString( "taxNumber" ) );//纳税⼈识别号
                String businessScope = Util.null2String( rs.getString( "businessScope" ) );//经营范围
                String regLocation = Util.null2String( rs.getString( "regLocation" ) );//注册地址
                String regCapitalCurrency = Util.null2String( rs.getString( "regCapitalCurrency" ) );//注册资本币种 ⼈⺠币 美元 欧元 等
                String tags = Util.null2String( rs.getString( "tags" ) );//企业标签
                String district = Util.null2String( rs.getString( "district" ) );//区
                String name = Util.null2String( rs.getString( "name" ) );//企业名
                String bondType = Util.null2String( rs.getString( "bondType" ) );//股票类型
                String percentileScore = Util.null2String( rs.getString( "percentileScore" ) );//企业评分
                String isMicroEnt = Util.null2String( rs.getString( "isMicroEnt" ) );//是否是⼩微企业 0不是 1是
                String base = Util.null2String( rs.getString( "base" ) );//省份简称
                datas.put( "historyNames", historyNames );//曾⽤名
                datas.put( "regStatus", regStatus );//企业状态
                datas.put( "cancelDate", cancelDate );//注销⽇期
                datas.put( "regCapital", regCapital );//注册资本
                datas.put( "city", city );//市
                datas.put( "staffNumRange", staffNumRange );//⼈员规模
                datas.put( "industry", industry );//⾏业
                datas.put( "historyNameList", historyNameList );//曾⽤名列表
                datas.put( "bondNum", bondNum );//股票号
                datas.put( "type", type );//法⼈类型，1 ⼈ 2 公司
                datas.put( "bondName", bondName );//股票名
                datas.put( "updateTimes", updateTimes );//更新时间
                datas.put( "revokeDate", revokeDate );//吊销⽇期
                datas.put( "legalPersonName", legalPersonName );//法⼈
                datas.put( "revokeReason", revokeReason );//吊销原因
                datas.put( "regNumber", regNumber );//注册号
                datas.put( "property3", property3 );//英⽂名
                datas.put( "creditCode", creditCode );//统⼀社会信⽤代码
                datas.put( "usedBondName", usedBondName );//股票曾⽤名
                datas.put( "fromTime", fromTime );//经营开始时间
                datas.put( "approvedTime", approvedTime );//核准时间
                datas.put( "socialStaffNum", socialStaffNum );//参保⼈数
                datas.put( "alias", alias );//简称
                datas.put( "companyOrgType", companyOrgType );//企业类型
                datas.put( "actualCapitalCurrency", actualCapitalCurrency );//实收注册资本币种 ⼈⺠币 美元 欧元 等
                datas.put( "qyid", qyid );//企业id
                datas.put( "orgNumber", orgNumber );//组织机构代码
                datas.put( "cancelReason", cancelReason );//注销原因
                datas.put( "toTime", toTime );//经营结束时间
                datas.put( "actualCapital", actualCapital );//实收注册资⾦
                datas.put( "estiblishTime", estiblishTime );//成⽴⽇期
                datas.put( "regInstitute", regInstitute );//登记机关
                datas.put( "taxNumber", taxNumber );//纳税⼈识别号
                datas.put( "businessScope", businessScope );//经营范围
                datas.put( "regLocation", regLocation );//注册地址
                datas.put( "regCapitalCurrency", regCapitalCurrency );//注册资本币种 ⼈⺠币 美元 欧元 等
                datas.put( "tags", tags );//企业标签
                datas.put( "district", district );//区
                datas.put( "name", name );//企业名
                datas.put( "bondType", bondType );//股票类型
                datas.put( "percentileScore", percentileScore );//企业评分
                datas.put( "isMicroEnt", isMicroEnt );//是否是⼩微企业 0不是 1是
                datas.put( "base", base );//省份简称
                //明细数据
                JSONObject industryAll = new JSONObject();
                rs1.executeQuery( "select categorymiddle,categorybig,category,categorysmall from uf_tycqyxx_dt1 where mainid=?", mainid );
                rs1.next();
                String categoryMiddle = Util.null2String( rs1.getString( "categoryMiddle" ) );//国⺠经济⾏业分类中类
                String categoryBig = Util.null2String( rs1.getString( "categoryBig" ) );//国⺠经济⾏业分类⼤类
                String category = Util.null2String( rs1.getString( "category" ) );//国⺠经济⾏业分类⻔类
                String categorySmall = Util.null2String( rs1.getString( "categorySmall" ) );//国⺠经济⾏业分类⼩类
                industryAll.put( "categoryMiddle", categoryMiddle );
                industryAll.put( "categoryBig", categoryBig );
                industryAll.put( "category", category );
                industryAll.put( "categorySmall", categorySmall );
                datas.put( "industryAll", industryAll );
            } else {
                out.println( "-------------------------22222<br/>" );
                rs.executeUpdate( "delete uf_tycqyxx where id=?", mainid );
                rs.executeUpdate( "delete uf_tycqyxx_dt1 where mainid=?", mainid );
                String url = baseBean.getPropValue( "tianyancha", "url" );
                String TOKEN = baseBean.getPropValue( "tianyancha", "token" );
                String URL = url + "?keyword=" + keyword;
                String CODE = "UTF-8";
                JSONObject resultJson = sendGetHttpRequest( URL, TOKEN, CODE );
                String reason = resultJson.getString( "reason" );//错误信息
                String errorcode = resultJson.getString( "error_code" );//状态码
                JSONObject result = JSONObject.parseObject( resultJson.getString( "result" ) );
                if ("ok".equals( reason ) && "0".equals( errorcode )) {
                    datas.put( "result", result );
                    if (addBusinessInfo( result )) {
                        addLogInfo( addressIP, errorcode, reason, keyword );
                    }
                }
            }
        } else {
            out.println( "-------------------------22222<br/>" );
            String url = baseBean.getPropValue( "tianyancha", "url" );
            String TOKEN = baseBean.getPropValue( "tianyancha", "token" );
            String URL = url + "?keyword=" + keyword;
            String CODE = "UTF-8";
            JSONObject resultJson = sendGetHttpRequest( URL, TOKEN, CODE );
            String reason = resultJson.getString( "reason" );//错误信息
            String errorcode = resultJson.getString( "error_code" );//状态码
            out.println( "-------------------------reason=" + reason + "<br/>" );
            out.println( "-------------------------errorcode" + errorcode + "<br/>" );
            JSONObject result = JSONObject.parseObject( resultJson.getString( "result" ) );
            if ("ok".equals( reason ) && "0".equals( errorcode )) {
                datas.put( "result", result );
                if (addBusinessInfo( result )) {
                    addLogInfo( addressIP, errorcode, reason, keyword );
                }
            }
        }
        out.println( "datas=" + datas + "<br/>" );
        apidatas.put( "datas", datas );
        apidatas.put( "api_status", true );
    } catch (Exception e) {
        e.printStackTrace();
        apidatas.put( "api_status", false );
        apidatas.put( "error_message", "获取天眼查数据异常" );
    }
%>
<%!
    //天眼查-企业基本信息入库
    public static boolean addBusinessInfo(JSONObject result) {
        boolean flag = false;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        String historynames = Util.null2String( result.getString( "historyNames" ) );//曾⽤名
        String regstatus = Util.null2String( result.getString( "regStatus" ) );//企业状态
        String canceldate = Util.null2String( result.getString( "cancelDate" ) );//注销⽇期
        String regcapital = Util.null2String( result.getString( "regCapital" ) );//注册资本
        String city = Util.null2String( result.getString( "city" ) );//市
        String staffnumrange = Util.null2String( result.getString( "staffNumRange" ) );//⼈员规模
        String industry = Util.null2String( result.getString( "industry" ) );//⾏业
        String historynamelist = Util.null2String( result.getString( "historyNameList" ) );//曾⽤名列表
        String bondnum = Util.null2String( result.getString( "bondNum" ) );//股票号
        String type = Util.null2String( result.getString( "type" ) );//法⼈类型，1 ⼈ 2 公司
        String bondname = Util.null2String( result.getString( "bondName" ) );//股票名
        String updatetimes = Util.null2String( result.getString( "updateTimes" ) );//更新时间
        String revokedate = Util.null2String( result.getString( "revokeDate" ) );//吊销⽇期
        String legalpersonname = Util.null2String( result.getString( "legalPersonName" ) );//法⼈
        String revokereason = Util.null2String( result.getString( "revokeReason" ) );//吊销原因
        String regnumber = Util.null2String( result.getString( "regNumber" ) );//注册号
        String property3 = Util.null2String( result.getString( "property3" ) );//英⽂名
        String creditcode = Util.null2String( result.getString( "creditCode" ) );//统⼀社会信⽤代码
        String usedbondname = Util.null2String( result.getString( "usedBondName" ) );//股票曾⽤名
        String fromtime = Util.null2String( result.getString( "fromTime" ) );//经营开始时间
        String approvedtime = Util.null2String( result.getString( "approvedTime" ) );//核准时间
        String socialstaffnum = Util.null2String( result.getString( "socialStaffNum" ) );//参保⼈数
        String alias = Util.null2String( result.getString( "alias" ) );//简称
        String companyorgtype = Util.null2String( result.getString( "companyOrgType" ) );//企业类型
        String actualcapitalcurrency = Util.null2String( result.getString( "actualCapitalCurrency" ) );//实收注册资本币种 ⼈⺠币 美元 欧元 等
        String qyid = Util.null2String( result.getString( "id" ) );//企业id
        String orgnumber = Util.null2String( result.getString( "orgNumber" ) );//组织机构代码
        String cancelreason = Util.null2String( result.getString( "cancelReason" ) );//注销原因
        String totime = Util.null2String( result.getString( "toTime" ) );//经营结束时间
        String actualcapital = Util.null2String( result.getString( "actualCapital" ) );//实收注册资⾦
        String estiblishtime = Util.null2String( result.getString( "estiblishTime" ) );//成⽴⽇期
        String reginstitute = Util.null2String( result.getString( "regInstitute" ) );//登记机关
        String taxnumber = Util.null2String( result.getString( "taxNumber" ) );//纳税⼈识别号
        String businessscope = Util.null2String( result.getString( "businessScope" ) );//经营范围
        String reglocation = Util.null2String( result.getString( "regLocation" ) );//注册地址
        String regcapitalcurrency = Util.null2String( result.getString( "regCapitalCurrency" ) );//注册资本币种 ⼈⺠币 美元 欧元 等
        String tags = Util.null2String( result.getString( "tags" ) );//企业标签
        String district = Util.null2String( result.getString( "district" ) );//区
        String name = Util.null2String( result.getString( "name" ) );//企业名
        String bondtype = Util.null2String( result.getString( "bondType" ) );//股票类型
        String percentilescore = Util.null2String( result.getString( "percentileScore" ) );//企业评分
        String ismicroent = Util.null2String( result.getString( "isMicroEnt" ) );//是否是⼩微企业 0不是 1是
        String base = Util.null2String( result.getString( "base" ) );//省份简称
        JSONObject industryall = JSONObject.parseObject( result.getString( "industryAll" ) );//国⺠经济⾏业分类
        String categorymiddle = Util.null2String( industryall.getString( "categoryMiddle" ) );//国⺠经济⾏业分类中类
        String categorybig = Util.null2String( industryall.getString( "categoryBig" ) );//国⺠经济⾏业分类⼤类
        String category = Util.null2String( industryall.getString( "category" ) );//国⺠经济⾏业分类⻔类
        String categorysmall = Util.null2String( industryall.getString( "categorySmall" ) );//国⺠经济⾏业分类⼩类
        String currentdate = DateUtil.getFullDate();
        String sql = "insert into uf_tycqyxx(currentdate,type1,qyid,historynames,regstatus,canceldate," +
                "regcapital,city,staffnumrange,industry,historynamelist,bondnum,bondname,updatetimes,revokedate," +
                "legalpersonname,revokereason,regnumber,property3,creditcode,usedbondname,fromtime,approvedtime," +
                "socialstaffnum,alias,companyorgtype,actualcapitalcurrency,orgnumber,cancelreason,totime," +
                "actualcapital,estiblishtime,reginstitute,taxnumber,businessscope,reglocation,regcapitalcurrency," +
                "tags,district,name,bondtype,percentilescore,ismicroent,base) values (?,?,?,?,?,?,?,?,?,?,?,?,?," +
                "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        Object[] params = {currentdate, type, qyid, historynames, regstatus, canceldate, regcapital, city, staffnumrange,
                industry, historynamelist, bondnum, bondname, updatetimes, revokedate, legalpersonname, revokereason,
                regnumber, property3, creditcode, usedbondname, fromtime, approvedtime, socialstaffnum, alias, companyorgtype,
                actualcapitalcurrency, orgnumber, cancelreason, totime, actualcapital, estiblishtime, reginstitute, taxnumber,
                businessscope, reglocation, regcapitalcurrency, tags, district, name, bondtype, percentilescore, ismicroent, base};
        if (rs.executeUpdate( sql, params )) {
            rs1.executeQuery( "select id from uf_tycqyxx where creditcode=?", creditcode );
            rs1.next();
            String mainid = Util.null2String( rs1.getString( "id" ) );//mainid
            rs.writeLog( "------------------------mainid=" + mainid );
            Object[] params1 = {mainid, categorymiddle, categorybig, category, categorysmall};
            String sql1 = "insert into uf_tycqyxx_dt1(mainid,categorymiddle,categorybig,category,categorysmall) values (?,?,?,?,?)";
            rs1.executeUpdate( sql1, params1 );
            flag = true;
        }

        return flag;
    }

    //插入天眼查接口调用日志
    public static boolean addLogInfo(String clientip, String errorcode, String reason, String keyword) {
        RecordSet rs = new RecordSet();
        boolean flag = false;
        String name = "http://open.api.tianyancha.com/services/open/ic/baseinfo/normal";//接口名称
        String createdate = DateUtil.getFullDate();
        ;//调用时间
        String times = "1";//调用次数
        UUID MR_UUID = UUID.randomUUID();
        String uuid = MR_UUID.toString();
        String sql = "insert into uf_tycinvokelog (name,clientip,errorcode,reason,createdate,times,keyword,uuid) " +
                "values (?,?,?,?,?,?,?,?)";
        Object[] params = {name, clientip, errorcode, reason, createdate, times, keyword, uuid};
        if (rs.executeUpdate( sql, params )) {
            flag = true;
        }
        return flag;
    }

    //获取天数
    public static long getDays(String date) {
        long days = 0L;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
            Date d1 = sdf.parse( date );
            long ts1 = d1.getTime();
            Date d2 = sdf.parse( DateUtil.getCurrentDate() );
            long ts2 = d2.getTime();
            days = (ts2 - ts1) / (1000 * 60 * 60 * 24);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return days;
    }

    public static JSONObject sendGetHttpRequest(String url, String token, String URLCode) {
        BaseBean baseBean = new BaseBean();
        // get请求返回结果
        JSONObject jsonResult = null;
        CloseableHttpClient client = HttpClients.createDefault();
        // 发送get请求
        HttpGet request = new HttpGet( url );
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout( 6000 ).setConnectTimeout( 6000 ).build();
        request.setConfig( requestConfig );
        request.setHeader( "Authorization", token );//token值
        try {
            CloseableHttpResponse response = client.execute( request );
            //请求发送成功，并得到响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //读取服务器返回过来的json字符串数据
                HttpEntity entity = response.getEntity();
                String strResult = EntityUtils.toString( entity, URLCode );
                //把json字符串转换成json对象
                jsonResult = JSONObject.parseObject( strResult );
            } else {
                baseBean.writeLog( "get请求提交失败:" + url );
            }
        } catch (IOException e) {
            baseBean.writeLog( "get请求提交失败:" + e );
        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }
%>